package com.wxmit.ot.gen.controller;

import com.wxmit.ot.base.ApiResult;
import com.wxmit.ot.base.core.OtBaseController;
import com.wxmit.ot.gen.domain.GenTable;
import com.wxmit.ot.gen.domain.dto.GenCodePreviewDto;
import com.wxmit.ot.gen.domain.dto.GenTableInitDto;
import com.wxmit.ot.gen.service.GenTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * GenGroupController
 * @author huangxiong
 * @version V1.0
 * @date 2023/2/22 10:50
 */
@RestController
@RequestMapping("/gen/table")
@Slf4j
public class GenTableController extends OtBaseController<GenTableService, GenTable,Long> {

    public GenTableController(GenTableService baseService) {
        super(baseService);
    }

    @PostMapping("/initDto")
    public ApiResult<Long> initGenTable(@RequestBody @Validated GenTableInitDto genTableInitDto){
        Long id = baseService.addByInitGenTable(genTableInitDto);
        return ApiResult.successWithData(id);
    }

    @Override
    public ApiResult<GenTable> get(@PathVariable("id") Long id) {
        return ApiResult.successWithData(baseService.getByIdWithColumn(id));
    }

    @GetMapping("doGen/{id}")
    public void genCode(@PathVariable("id") Long id,HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"oneThingCodeGen.${System.currentTimeMillis()}.zip\"");
        response.setContentType("application/octet-stream; charset=UTF-8");
        baseService.genCodeById(id,outputStream);
    }

    @GetMapping("preview/{id}")
    public ApiResult<List<GenCodePreviewDto>> preview(@PathVariable("id") Long id){
        return ApiResult.successWithData(baseService.preview(id));
    }
}
